<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Access\User\User;
use Illuminate\Support\Facades\DB;

class encryption_users_fields extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:encrypt';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'encryption a users field';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if ($this->confirm('Do you wish to continue? [y|N]')) {

            $where = [['email','like','%@%'],['email','like','%.%']];
            $users = DB::table('users')->where($where)->get();

            $error = false;
            foreach ($users as $user){
                if (filter_var($user->email,FILTER_VALIDATE_EMAIL)){

                    $email =  encrypt_func($user->email,$user->name);

                    $phone = filter_var(intval($user->phone),FILTER_VALIDATE_INT) ? encrypt_func($user->phone,$user->name) : $user->phone;
                    DB::connection()->enableQueryLog();
                    if(!DB::table('users')->where(['id'=>$user->id])->update(['email'=>$email,'phone'=>$phone])){
                        \Log::info(json_encode(DB::getQueryLog())."\r\n");
                        $error = true;
                    }
                } else {
                    $error = true;

                    \Log::info($user->email . "，邮箱号不合法\r\n");
                }
            }
            if ($error){
                dd('error:Please check the failure record in the log file');
            } elseif ($users->isEmpty()) {
                dd('No records are found that you need to encrypt');
            } else {

                dd('success');
            }
        }
    }
}
